package com.zebra.remoting.tms;


import cn.hutool.core.util.StrUtil;
import com.zebra.common.concurrent.ZebraExecutorManager;
import com.zebra.remoting.*;
import com.zebra.remoting.config.TmsServerInfo;
import com.zebra.remoting.protocol.CommandCode;
import com.zebra.remoting.protocol.CommandModelManager;
import com.zebra.remoting.protocol.ZebraCodec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class TmsServerApplication {

    @Value("${zebra.port}")
    private int nettyPort;

    @Value("${zebra.weight}")
    private int weight;

    @Value("${spring.application.name}")
    private String appName;

    /**
     * run tms server
     * @param commandCodeMap   命令对应 cmd : commandCode
     * @param zebraHandlerService  对应cmd handler
     * @param serverInfo    需要  vfxs  gameIds
     * @throws Exception
     */
    public void run(IpInfoProperties properties, Map<Integer, CommandCode> commandCodeMap, AbstractServerHandler zebraHandlerService, AbstractOnlineNumberService onlineNumberService, TmsServerInfo serverInfo) throws Exception {
        if (null == zebraHandlerService){
            throw  new Exception("TmsServerHandler is null");
        }
        if (serverInfo == null || StrUtil.isEmpty(serverInfo.getGameIds())){
            throw  new Exception("serverInfo gamids is null");
        }

        if (nettyPort < 5000 || nettyPort > 65535){
            throw new Exception("port lg 5000 or gt 65535");
        }

        if (null == commandCodeMap || commandCodeMap.isEmpty()){
            throw new Exception("CommandCodeMap is null");
        }

        if (null == properties || properties.isNull()){
            throw new Exception("IpInfoProperties is null");
        }

        CommandModelManager.initializeCommandCode(commandCodeMap);


        serverInfo.setAppName(appName);
        serverInfo.setInIP(properties.getIpIn());
        serverInfo.setOutIP(properties.getIpOut());
        serverInfo.setPort(nettyPort);
        serverInfo.setWeight(weight);
        serverInfo.setCmds(CommandModelManager.buildCmds());

        RemotingServer server = new ZebraRpcServer();
        server.registerRpcCodec(new ZebraCodec());
        server.registerCommandHandler(zebraHandlerService);
        if (!server.start(nettyPort)) {
            throw  new Exception("server start failure");
        }

        // start success serverInfo set mananger
        TmsConfigInfoManager.getInstance().setServerInfo(serverInfo); //调用了注册中心 注册之后 需要把最新的serverInfo set to 本地缓存
        TmsExecutorManager.getInstance().start(20);
        ZebraExecutorManager.getInstance().start(16);
        onlineNumberService.start();
    }



}
